##### GLOBALS #####
# Load packages
library(mFilter)

# Read data
sp500 <- read.csv("SP_500.csv") # S&P 500 Data
tb_issuance <- read.csv("TB_Issuance.csv") # Monthly TB Issuance Data

##### HP Analysis (S&P 500) #####
# HP Filters
sp500$ru_smoothed <- hpfilter(sp500$adj_close_price, # data
                              type = "lambda", # use lambda method
                              freq = 123600)$ trend # extract trend at lambda = 123600

sp500$hp_smoothed <- hpfilter(sp500$adj_close_price, # data
                              type = "lambda", # use lambda method
                              freq = 14400)$trend # extract trend at lambda = 14400

# Add Time index
sp500$time_index <- seq_along(sp500$date)

# Plot
plot(x = sp500$time_index,
     y = sp500$adj_close_price,
     col = "red",
     type = "l",
     ylab = "Price (USD)",
     xlab = "Time",
     main = "Inflation-Adjusted S&P 500",
     xaxt = "n",
     ylim = c(0, 2500))

# Add HP line
lines(x = sp500$time_index,
      y = sp500$hp_smoothed,
      col = "blue",
      lty = 1)

# Add RU line
lines(x = sp500$time_index,
      y = sp500$ru_smoothed,
      col = "forestgreen",
      lty = 1)


# Add legend
legend(x = "topleft",
       inset = 0.01,
       legend = c("Data","λ = 14,400","λ = 123,600"),
       fill = c("red", "blue", "forestgreen"))

##### HP Analysis (Treasury) #####
# Subset by country (US Only)
us_tbi <- tb_issuance[tb_issuance$treatment == 1, ]

# Create index column
us_tbi$index <- 1:nrow(us_tbi)

# Adjust into billions
us_tbi$real_issue <- us_tbi$real_issue / 1000

# Create HP filters
us_tbi$ru_smoothed <- hpfilter(us_tbi$real_issue, # data
                               type = "lambda", # use lambda method
                               freq = 123600)$ trend # extract trend at lambda = 123600

us_tbi$hp_smoothed <- hpfilter(us_tbi$real_issue, # data
                               type = "lambda", # use lambda method
                               freq = 14400)$trend # extract trend at lambda = 14400

# Plot
plot(x = us_tbi$index,
     y = us_tbi$real_issue,
     col = "red",
     type = "l",
     ylab = "Issuance (Billions of USD)",
     xlab = "Time",
     main = "US Real Monthly Treasury Auctions",
     xaxt = "n",
     ylim = c(100, 600))

# Add HP line
lines(us_tbi$index,
      us_tbi$hp_smoothed,
      col = "blue")

# Add RU line
lines(us_tbi$index,
      us_tbi$ru_smoothed,
      col = "forestgreen")

# Add legend
legend(x = "topleft",
       inset = 0.01,
       legend = c("Data","λ = 14,400","λ = 123,600"),
       fill = c("red", "blue", "forestgreen"))

##### DiD Model #####
did_model <- lm(real_issue ~
                  treatment +
                  period +
                  interaction,
                data = tb_issuance)